import React, { useRef } from 'react';
import Cropper from 'react-cropper';
import { Button, message } from 'antd';
import 'cropperjs/dist/cropper.css';
import services from '../../services/api';

import Modal from '../Modal';

export default function CropperImg({ id, url, onCallback }) {
  const cropper = useRef(null);
  const model = useRef(null);
  function renderCropper() {
    return (
      <Cropper
        ref={cropper}
        src={url}
        style={{ height: 500, width: '100%' }}
        aspectRatio={16 / 16}
        guides={false}
      />
    );
  }
  function cropSubmit() {
    const { width, height, x, y } = cropper.current.getData();
    services
      .cropImg(id, {
        url: url,
        x: x,
        y: y,
        w: width,
        h: height
      })
      .then(res => {
        if (res.code === 0) {
          onCallback && onCallback(res.data);
          Modal.close();
        } else {
          message.error(res.msg);
        }
      });
  }
  function startCropper() {
    model.current = Modal.open({
      title: '裁剪图片',
      content: <div>{renderCropper()}</div>,
      okTxt: '保存',
      cancelTxt: '取消',
      isOkBtn: true,
      isCancelBtn: true,
      width: 800,
      maskClosable: true,
      ok: () => {
        cropSubmit();
        //   Modal.close(index);
      },
      cancel: () => {
        Modal.close(model.current);
      }
    });
  }
  return <Button onClick={() => startCropper()}>设为缩略</Button>;
}
